package com.uroad.liaoningpos.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.ums.AppHelper;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.CurrApplication;
import com.uroad.liaoningpos.common.GlobalData;
import com.uroad.liaoningpos.common.PrintServiceResult;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.model.PayDetailMDL;
import com.uroad.liaoningpos.model.PayResultMDL;
import com.uroad.liaoningpos.model.TransData;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.sys.SystemUtil;
import com.uroad.lib.widget.dialog.ComfirmDialog;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.json.JSONException;

import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.uroad.liaoningpos.webService.PosWS.pay;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 20:35
 * @描述 订单撤销
 */
public class OrderCancelActivity extends BaseActivity {
    private static final int REQUEST_CODE_CANCEL = 10;
    private String TAG = "OrderCancelActivity";
    @BindView(R.id.tvCancelTrip)
    TextView tvCancelTrip;
    @BindView(R.id.etCancelNo)
    EditText etCancelNo;
    private String cancelNo = "";
    private TransData transData;
    private String type = "";
    private String posimei = "";
    private String orderno = "";
    private String voucherno = "";
    private String time = "";
    private String terminalno = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_order_cancel);
        ButterKnife.bind(this);
        setTitle("订单撤销");
        initIntentData();
        initListener();
    }

    private void initIntentData() {
        terminalno = (String) SPUtils.get(this, SPContants.SP_TERMINALNO, "");
        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
        Bundle bundle  = getIntent().getExtras();;
        if (bundle != null) {
            type = bundle.getString("type");
        }
    }

    private void initListener() {
        //edittext 软键盘监听
        etCancelNo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    //软键盘完成按钮
                    case EditorInfo.IME_ACTION_DONE:
                        cancelNo = etCancelNo.getText().toString().trim();
                        if (TextUtils.isEmpty(cancelNo)) {
                            showShortToast("请输入要撤销订单的凭证号");
                        }else{
                            showConfirmDialog();
                        }
                        break;
                    default:
                }
                return true;
            }
        });
    }

    private void showConfirmDialog() {
        DialogHelper.showComfirmDialog(this, "提示",
                "确定要撤销订单：" + cancelNo + "吗？", "取消", "确定",
                new ComfirmDialog.DialogOnclick() {
                    @Override
                    public void PerDialogclick(Dialog dialog) {
                        dialog.dismiss();
                    }
                }, new ComfirmDialog.DialogOnclick() {
                    @Override
                    public void PerDialogclick(Dialog dialog) {
                        dialog.dismiss();
                        getOrderNo();
                        //                        orderCancel();
                        //                org.json.JSONObject json = null;
                        //                try {
                        //                    json = new org.json.JSONObject("{\"useScan\":\"false\",\"orgTraceNo\":\"" + cancelNo + "\"}");
                        //                } catch (JSONException e) {
                        //                    e.printStackTrace();
                        //                }
                        //                AppHelper.callTrans(OrderCancelActivity.this, "公共资源", "撤销", json);
                    }
                });
    }
    //根据流水号查询订单号
    private void getOrderNo() {
        DialogHelper.showLoading(this, "");
        doRequest(PosWS.ordernofind, PosWS.ordernofindParams(cancelNo), PosWS.ordernofind);
    }

    private void newlandCancel(){
        String str = "payment://com.newland.pospp/paymentVoid?outOrderNo="+orderno+"1"+ //+1防止外部订单号重复
                "&oriVoucherNo="+cancelNo;

        Uri uri = Uri.parse(str);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivityForResult(intent, 1);
    }

    private void orderCancel() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.yada.spos.cashierplatfrom",
                "com.yada.spos.cashierplatfrom.InvokeActivity"));
     /*   intent.setPackage(GlobalData.YADA_PKG);
        if ("scan".equals(type)) {
            intent.setAction(GlobalData.YADA_CLASS_SCAN);
            intent.putExtra("channelId", "unionscan");
        }else {
            intent.setAction(GlobalData.YADA_CLASS);
            intent.putExtra("channelId", "acquire");
        }*/
        //中行间连参数
        intent.putExtra("channelName","cardPay");
        intent.putExtra("tranType",type);
        intent.putExtra("appOrderNo", orderno);
        intent.putExtra("traceNo",cancelNo);
        intent.putExtra("cardNo", "");
        intent.putExtra("expDate","");
        intent.putExtra("payVoucherNum",voucherno);
        intent.putExtra("orderNo","");
        intent.putExtra("isOpenAdminVerify",false);

     /*   //中行直连参数
        intent.putExtra("transType",7);
        intent.putExtra("operatorNo","01");
        intent.putExtra("oriVoucherNo", cancelNo);
//        intent.putExtra("oriTransTime", time);
//        intent.putExtra("outOrderNo", orderno);
        intent.putExtra("isOpenAdminVerify", false);
        intent.putExtra("remark", "");*/
        startActivityForResult(intent,REQUEST_CODE_CANCEL);
    }

    private void cancel() {
        DialogHelper.showLoading(this,"正在提交");
        doRequest(PosWS.payrevoke, PosWS.payrevokeParams(cancelNo,transData.getTraceNo(),
                transData.getMerchantNo(),transData.getTerminalNo()), PosWS.payrevoke);
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        DialogHelper.endLoading();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (FastJsonUtils.getJsonStatu00(jsonObject)) {
            if (PosWS.paylist.equals(id)) {
                JSONObject data = jsonObject.getJSONObject("data");
                List<PayDetailMDL> payDetailMDLS = FastJsonUtils.parseArrayJSON(data.getString("paylist"), PayDetailMDL.class);
                if (payDetailMDLS != null) {
                    for (PayDetailMDL mdl : payDetailMDLS) {
                        if ("91".equals(type)) {
                            if (cancelNo.equals(mdl.getVoucherno())) {
                                orderno = mdl.getOrderno();
                                time = mdl.getModified();
                            }
                        }else{
                            if (cancelNo.equals(mdl.getTraceno())) {
                                orderno = mdl.getOrderno();
                                time = mdl.getModified();
                            }
                        }
                    }
                }
            } else if (PosWS.ordernofind.equals(id)) {
                JSONObject data = jsonObject.getJSONObject("data");
//                orderno = data.getString("orderno");
                orderno = data.getString("ordernos");
                voucherno = data.getString("voucherno");
                String typePay = data.getString("type");
                if ("1".equals(typePay)) {
                    if (type.equals("106")){
//                        orderCancel();
                        newlandCancel();
                    }else {
                        showShortToast("请输入正确的订单凭证号");
                    }
                }else {
                    if (type.equals("91")){
                        newlandCancel();
//                        orderCancel();
                    }else {
                        showShortToast("请输入正确的订单凭证号");
                    }
                }
            } else if (PosWS.payrevoke.equals(id)) {
                showShortToast("撤销成功");
                etCancelNo.setText("");
            }
        }else{
            showShortToast(FastJsonUtils.getErrMsg00(jsonObject));
            if (PosWS.payrevoke.equalsIgnoreCase(id)) {
                CurrApplication.daoUtils.insert(transData);
                showShortToast("撤销上传失败，请联系维护人员");
            }
        }
    }

    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        DialogHelper.endLoading();
        if (PosWS.payrevoke.equalsIgnoreCase(msg)) {
            CurrApplication.daoUtils.insert(transData);
            showShortToast("撤销上传失败，请联系维护人员");
        }
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        if (PosWS.payrevoke.equalsIgnoreCase(msg)) {
            CurrApplication.daoUtils.insert(transData);
            showShortToast("撤销上传失败，请联系维护人员");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DialogHelper.endLoading();
        if (REQUEST_CODE_CANCEL == requestCode) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                switch (resultCode) {
                    case 0:
                        String msg = bundle.getString("msg");
                        if (!TextUtils.isEmpty(msg)) {
                            showShortToast(msg);
                        }
                        break;
                    case 1:
                        transData = new TransData();
                        transData.setTraceNo(bundle.getString("traceNo"));
//                        transData.setVoucherNo(bundle.getString(voucherno));
                        transData.setVoucherNo(cancelNo);
                        transData.setMerchantNo(bundle.getString("merchantId"));
                        transData.setTerminalNo(bundle.getString("terminalId"));
                        cancel();
                        break;
                }
            }
        } else if (AppHelper.TRANS_REQUEST_CODE == requestCode) {
            LogUtil.d(TAG, "resultCode" + resultCode);
            if (Activity.RESULT_OK == resultCode) {
                if (null != data) {
                    Log.i(TAG, "requestCode----->" + requestCode + "\nresultCode----->" + resultCode + "\ndata Extra(result)" + data.getStringExtra("result"));
                    getPayResult(data);
                } else {
                    LogUtil.i(TAG, "Intent is null" + "\n");
                }
            } else {
                LogUtil.i(TAG, "resultCode is not RESULT_OK" + "\n");
            }
        } else if (-1 == resultCode) {
            Log.d("LOG", data.getStringExtra("resultCode") + "");//具体的code见ServiceResult
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String responseCode = bundle.getString("responseCode");
                if ("00".equals(responseCode)) {
                    transData = new TransData();
                    transData.setResponseCode(responseCode);
                    transData.setTraceNo(bundle.getString("voucherNo"));
                    transData.setVoucherNo(bundle.getString("oriVoucherNo"));
                    transData.setMerchantNo(bundle.getString("merchantId"));
                    transData.setTerminalNo(bundle.getString("terminalId"));
                    cancel();
                }else {
                    String msg = bundle.getString("message");
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToast(msg);
                    }
                }
            }
        } else {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                String msg = bundle.getString("message");
                if (!TextUtils.isEmpty(msg)) {
                    showShortToast(msg);
                }
            }
        }
    }

    private void getPayResult(Intent data) {
        StringBuilder result = new StringBuilder();
        Map<String, String> map = AppHelper.filterTransResult(data);
        result.append("{\"" + AppHelper.TRANS_APP_NAME + "\":\"" + map.get(AppHelper.TRANS_APP_NAME) + "\",");
        result.append("\"" + AppHelper.TRANS_BIZ_ID + "\":\"" + map.get(AppHelper.TRANS_BIZ_ID) + "\",");
        result.append("\"" + AppHelper.RESULT_CODE + "\":\"" + map.get(AppHelper.RESULT_CODE) + "\",");
        result.append("\"" + AppHelper.RESULT_MSG + "\":\"" + map.get(AppHelper.RESULT_MSG) + "\",");
        result.append("\"" + AppHelper.TRANS_DATA + "\":" + map.get(AppHelper.TRANS_DATA) + "}");

        Log.i(TAG, "Activity调用 result = " + result.toString());
        if (null != result) {
            String json = result.toString();
            PayResultMDL resultMDL = FastJsonUtils.parseObjectJSON(json, PayResultMDL.class);
            if (resultMDL != null) {
                transData = resultMDL.getTransData();
                if ("00".equals(transData.getResCode())) {
                    cancel();
                } else {
                    showLongToast(resultMDL.getTransData().getResDesc());
                }
            }
        }
    }

}
